﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
using STMS.STMSApp.store_temperature;
using STMS.STMSApp.store;
using STMS.STMSApp.util;
using STMS.STMSApp.product;
using STMS.STMSApp.UControls;

namespace STMS.STMSApp
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        System.Timers.Timer timer = null;

        //初始化状态栏信息
        private void InitStatuInfo()
        {
            //用户名
            label_userName.Text = this.Tag.ToString();
            //时间 动态时间条-----计时器（Timers.Timer）
            label_time.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            timer = new System.Timers.Timer();
            timer.Interval = 1000;
            timer.AutoReset = true;
            timer.Elapsed += Timer_Elapsed;
            timer.Start();
        }

        //显示仓库管理页面
        private void ShowStoreManage()
        {
            setMenuBtnBackColor(1);
            StoreListForm storeListForm = new StoreListForm();
            FormUtil.AddFormToPanel(panel_content, storeListForm);
        }
        private void MainForm_Load(object sender, EventArgs e)
        {
            if(this.Tag != null)
            {
                //初始化状态栏信息
                InitStatuInfo();
                //显示仓库管理页面
                ShowStoreManage();

                button_closePage.Visible = true;
                RegisterPageBtnClick();

                initPageBtnTag();
            }
        }

        private void initPageBtnTag()
        {
            upb_storeManager.Tag = typeof(store.StoreListForm).FullName;
            upb_storeRegion.Tag = typeof(store.StoreRegionForm).FullName;

            upb_productManage.Tag = typeof(product.ProductInfoForm).FullName;
            upb_productInStore.Tag = typeof(product.ProductInStoreForm).FullName;

            upb_storeTemperatrue.Tag = typeof(store_temperature.SregionTemperatureForm).FullName;
        }

        /// <summary>
        /// 注册按钮单击事件
        /// </summary>
        private void RegisterPageBtnClick()
        {
            foreach(Control c in panelBtnTop.Controls)
            {
                if(c is UPageButton)
                {
                    UPageButton btn = c as UPageButton;
                    btn.Click += upb_menu_Click;
                }
            }
        }

        #region 左侧菜单
        private void menuBtn_store_Click(object sender, EventArgs e)
        {
            //显示仓库管理页面
            ShowStoreManage();
        }
        private void menuBtn_product_Click(object sender, EventArgs e)
        {
            setMenuBtnBackColor(2);
            //显示商品管理页面
            product.ProductInfoForm productInfoForm = new ProductInfoForm();
            FormUtil.AddFormToPanel(panel_content, productInfoForm);
        }

        private void menuBtn_regionTemperature_Click(object sender, EventArgs e)
        {
            setMenuBtnBackColor(3);
            //显示仓库分区温度管理界面
            store_temperature.SregionTemperatureForm sregionTemperatureForm = new SregionTemperatureForm();
            FormUtil.AddFormToPanel(panel_content,sregionTemperatureForm);
        }
        #endregion

        #region 初始化缩小、放大、关闭按钮
        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            this.Invoke(new Action(() =>
            {
                label_time.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            }));
        }
        //最小化按钮
        private void uIconButton_min_Click(object sender, EventArgs e)
        {
            if(this.WindowState != FormWindowState.Minimized)
                this.WindowState = FormWindowState.Minimized;
        }

        //最大化按钮
        private void uIconButton_max_Click(object sender, EventArgs e)
        {
            if(this.WindowState == FormWindowState.Maximized)
            {
                this.WindowState = FormWindowState.Normal;
                uIconButton_max.Text = "1";
            }else
            {
                this.WindowState = FormWindowState.Maximized;
                uIconButton_max.Text = "2";
            }
        }
        
        //关闭按钮
        private void uIconButton_close_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("是否退出系统?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                if(timer != null)
                    timer.Stop();
                Application.ExitThread();
            }
            else
                e.Cancel = true;
        }
        #endregion

        /// <summary>
        /// 菜单按钮的背景色
        /// </summary>
        /// <param name="code"></param>
        private void setMenuBtnBackColor(int code)
        {
            switch (code)
            {
                case 1:
                    //设置左侧仓库管理菜单按钮的背景颜色，其他两个按钮的背景颜色---默认
                    SetMenuBtnsColor(menuBtn_store, upb_storeManager);
                    break;
                case 2:
                    //设置左侧产品管理菜单按钮的背景颜色，其他两个按钮的背景颜色---默认
                    SetMenuBtnsColor(menuBtn_product, upb_productManage);
                    break;
                case 3:
                    //设置左侧仓库温度管理菜单按钮的背景颜色，其他两个按钮的背景颜色---默认
                    SetMenuBtnsColor(menuBtn_regionTemperature, upb_storeTemperatrue);
                    break;
            }
        }

        /// <summary>
        /// 处理左边按钮背景色和分页按钮的文本颜色
        /// </summary>
        /// <param name="btn"></param>
        /// <param name="btnPage"></param>
        private void SetMenuBtnsColor(UMenuButton btn, UPageButton btnPage)
        {
            //模块按钮的背景色
            Color unSelColor = Color.FromArgb(45, 50, 116);//未选中
            Color SelColor = Color.FromArgb(88, 116, 216);//选中
            //分页按钮文本颜色
            Color topSelColor = Color.FromArgb(45, 50, 116);//点击时或显示相关页面时
            Color topUnSelColor = Color.White;//默认或没有显示页面时

            btn.BackColor = SelColor;
            btnPage.ForeColor = topSelColor;

            //处理未选中模块按钮、未显示 分页按钮
            UMenuButton[] menuBtns = {menuBtn_store,menuBtn_product,menuBtn_regionTemperature};
            UPageButton[] pageBtns = {upb_storeManager,upb_storeRegion,upb_productManage,upb_productInStore,upb_storeTemperatrue};

            foreach (UMenuButton b in menuBtns)
            {
                if(b.Name!= btn.Name)
                    b.BackColor = unSelColor;
            }

            foreach (UPageButton b in pageBtns)
            {
                if (btnPage.Name != b.Name)
                    b.ForeColor = topUnSelColor;
            }
        }

        /// <summary>
        /// 分页按钮点击事件    
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void upb_menu_Click(object sender, EventArgs e)
        {
            //分页按钮文本颜色
            Color topSelColor = Color.FromArgb(45, 50, 116);//点击时或显示相关页面时
            Color topUnSelColor = Color.White;//默认或没有显示页面时

            UPageButton clickBtn = sender as UPageButton;//当前点击按钮

            foreach (Control c in panelBtnTop.Controls)
            {
                if (c is UPageButton)
                {
                    UPageButton btn = c as UPageButton;
                    if (btn.Name != clickBtn.Name)
                    {
                        btn.ForeColor = topUnSelColor;
                    }
                }
            }

            //切换页面的实现处理
            if(clickBtn.Tag != null)
            {
                string frmFullName = clickBtn.Tag.ToString();
                int lastIndex = frmFullName.LastIndexOf('.');
                string frmName = frmFullName.Substring(lastIndex + 1);

                Form f = FormUtil.GetOpenForm(frmName);
                if (f == null) 
                {
                    //实例化页面
                    f = (Form)Activator.CreateInstance(Type.GetType(frmFullName));
                }
                panel_content.AddFormToPanel(f);
                //处理关闭按钮的显示
                ShowClosePageBtn();
            }
        }

        /// <summary>
        /// 处理关闭页面按钮的显示
        /// </summary>
        private void ShowClosePageBtn()
        {
            if(panel_content.Controls.Count > 0)
            {
                button_closePage.Visible = true;
            }
            else
            {
                button_closePage.Visible = false;
            }
        }

        #region 移动窗体
        Point point = new Point();
        bool isMove = false;

        private void panel_top_MouseDown(object sender, MouseEventArgs e)
        {
            point = e.Location;//按住的点
            isMove = true;
        }

        private void panel_top_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && isMove)
            {
                Point pointNew = e.Location;//按住的点拖动到的位置
                Point fPointNew = new Point(pointNew.X - point.X, pointNew.Y - point.Y);//相对于原来起点的距离点的描述
                this.Location += new Size(fPointNew);

            }
        }
        #endregion

        #region 改变窗体大小
        const int WM_NCHITTEST = 0x0084;// 移动鼠标
        const int HTLEFT = 10;
        const int HTRIGHT = 11;
        const int HTTOP = 12;
        const int HTTOPLEFT = 13;
        const int HTTOPRIGHT = 14;
        const int HTBOTTOM = 15;
        const int HTBOTTOMLEFT = 0x10;
        const int HTBOTTOMRIGHT = 17;

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            switch (m.Msg)
            {
                case WM_NCHITTEST:
                    Point vPoint = new Point((int)m.LParam & 0xFFFF,
                   (int)m.LParam >> 16 & 0xFFFF);
                    vPoint = PointToClient(vPoint);
                    if (vPoint.X <= 5)
                        if (vPoint.Y <= 5)
                            m.Result = (IntPtr)HTTOPLEFT;
                        else if (vPoint.Y >= ClientSize.Height - 5)
                            m.Result = (IntPtr)HTBOTTOMLEFT;
                        else m.Result = (IntPtr)HTLEFT;
                    else if (vPoint.X >= ClientSize.Width - 5)
                        if (vPoint.Y <= 5)
                            m.Result = (IntPtr)HTTOPRIGHT;
                        else if (vPoint.Y >= ClientSize.Height - 5)
                            m.Result = (IntPtr)HTBOTTOMRIGHT;
                        else m.Result = (IntPtr)HTRIGHT;
                    else if (vPoint.Y <= 5)
                        m.Result = (IntPtr)HTTOP;
                    else if (vPoint.Y >= ClientSize.Height - 5)
                        m.Result = (IntPtr)HTBOTTOM;

                    break;
            }
        }
        #endregion

        /// <summary>
        /// 面板中的页面尺寸与面板的尺寸同步---面板中Form页自适应处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void panel_content_SizeChanged(object sender, EventArgs e)
        {
            foreach (Control c in panel_content.Controls)
            {
                Form f = c as Form;
                f.WindowState = FormWindowState.Normal;
                f.SuspendLayout();
                f.Size = panel_content.Size;
                //DataGridView 闪烁--- 先挂起  ，，，再恢复
                f.ResumeLayout();
                f.WindowState = FormWindowState.Maximized;
            }
        }
        /// <summary>
        /// 页关闭处理程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_closePage_Click(object sender, EventArgs e)
        {
            if (panel_content.Controls.Count > 0)
            {
                Form f = panel_content.Controls[0] as Form;
                f.Close();
                panel_content.Controls.Remove(f);
                //改变  分页按钮的字体颜色
                foreach(Control c in panelBtnTop.Controls)
                {
                    if(c is UPageButton)
                    {
                        UPageButton b = c as UPageButton;
                        if (b.Tag.ToString().Contains(f.Name) && b.Tag != null)
                        {
                            b.ForeColor = Color.White;
                            break;
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("没有可以关闭的页面！","错误提示");
                return;
            }
        }
    }
}
